<?php

declare(strict_types=1);

namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use Service\AppService\IdService;
use Hyperf\DbConnection\Db;
use App\Service\Code\Normal;

class Stock extends BasePssModel
{
    public $table = 'stock';
    
    /**
     * 扣除库存接口
     * @param array $keys
     */
    public function deductGoodsStock( $stockGoodsList = [] )
    {
        if( empty($stockGoodsList) ) {
            return Normal::returnCode(Normal::FAIL,"参数不能为空");
        }
        
        foreach ($stockGoodsList as $stock ) 
        {
            $stock_id = $stock['stock_id'];
            $number   = $stock['stock_number'];
            $cur_stock = Stock::instance()->info(['id' => $stock_id]);
            if( empty($cur_stock['number']) || $cur_stock['number'] <= 0 ) {
                return Normal::returnCode(Normal::FAIL,"当前商品【{$stock_id}】库存不足[000000]");
            }
            
            //获取当前数据版本
            $version  = $cur_stock['version'];
            
            //更新库存
            $up_res = Stock::instance()->where('id',$stock_id)
            ->where('version',$version)
            ->where('number','>',0)
            ->update([
                'number'    => Db::raw("number-{$number}"),
                'version'   => Db::raw("version+1"),
            ]);
            if( ! $up_res ) {
                return Normal::returnCode(Normal::FAIL,"当前商品【{$stock_id}】库存不足[000001]");
            }
            
            $res_add_log = StockLog::instance()->insert([
                'id'        => IdService::instance()->getOtherID(),
                'stock_id'  => $stock_id,
                'number'    => $number,
            ]);
            if( ! $res_add_log ) {
                return Normal::returnCode(Normal::FAIL,"当前商品【{$stock_id}】库存不足[000002]");
            }
        }
        return Normal::returnCode(Normal::SUC,"库存操作成功");
    }
}